package com.heima.wemedia.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author lcz
 * @since 2024-11-18
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        String name = multipartFile.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        String substring = name.substring(name.lastIndexOf("."));
        String url = null;
        try {
            url = fileStorageService.uploadHtmlFile("", uuid + substring, multipartFile.getInputStream());

        } catch (IOException e) {
            log.error("上传文件出错", e);
        }
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(url);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult queryMu(WmMaterialDto materialDto) {
        Page page = new Page<>(materialDto.getPage(), materialDto.getSize());
        Page p = lambdaQuery().eq(materialDto.getIsCollection() ==1, WmMaterial::getIsCollection, materialDto.getIsCollection())
                .orderByDesc(WmMaterial::getCreatedTime)
                .page(page);
        ResponseResult responseResult=new PageResponseResult(materialDto.getPage(),materialDto.getSize(),(int)p.getTotal());
        responseResult.setData(p.getRecords());

        return responseResult;
    }
}
